package dao

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go_test/src/code.song.study/web/model"
	"time"
)

const (
	Direct = "mysql"
	Url    = "root:MyNewPass4!@(192.144.176.99:3306)/crawler?charset=utf8mb4&parseTime=True&loc=Local"
)

var db *gorm.DB

// 引入该包时 进行连接初始化
func init() {
	db = newConnect()
}

// 初始化新连接
func newConnect() *gorm.DB {
	conn, err := gorm.Open(Direct, Url)
	if err != nil {
		fmt.Print("connect mysql err: ", err)
		return nil
	}
	fmt.Println("create db ....")
	conn.SingularTable(true)
	conn.LogMode(true)
	conn.DB().SetMaxIdleConns(10)                   //最大空闲连接数
	conn.DB().SetMaxOpenConns(30)                   //最大连接数
	conn.DB().SetConnMaxLifetime(time.Second * 300) //设置连接空闲超时
	return conn
}

// 获取 db 连接
func GetDB() *gorm.DB {
	if err := db.DB().Ping(); err != nil {
		db.Close()
		return newConnect()
	}
	return db
}

// 根据条件获取所有视频列表
func GetAllVideoInfoList(req model.VideoReqBO) []model.VideoInfo {
	var videoList []model.VideoInfo
	db := GetDB()
	offset := 0
	if req.PageNo > 0 && req.PageSize >= 0 {
		offset = (req.PageNo - 1) * req.PageSize
	}
	if req.Name == "" {
		db.Table("video_info").Offset(offset).Limit(req.PageSize).Order(" id desc ").Find(&videoList)
	} else {
		db.Table("video_info").Where(" video_name like ?", "%"+req.Name+"%").Offset(offset).Limit(req.PageSize).Order(" id desc ").Find(&videoList)
	}
	return videoList
}

func GetVideoInfoCount(req model.VideoReqBO) (count int) {
	db := GetDB()
	if req.Name == "" {
		db.Table("video_info").Limit(req.PageSize).Order(" id desc ").Count(&count)
	} else {
		db.Table("video_info").Where(" video_name like ?", "%"+req.Name+"%").Limit(req.PageSize).Order(" id desc ").Count(&count)
	}
	return
}

// 根据videoId 获取video info
func GetVideoDetailInfo(videoId int) (videoInfo model.VideoInfo) {
	db := GetDB()
	db.Table("video_info").Where(" id = ?", videoId).Find(&videoInfo)
	return videoInfo
}

func main() {
	req := model.VideoReqBO{
		Name: "31",
	}
	req.PageNo = 1
	req.PageSize = 10
	list := GetAllVideoInfoList(req)
	for _, item := range list {
		videoStr, _ := json.Marshal(item)
		fmt.Println(string(videoStr))
	}
}
